<template>
  <div class="point-details-section">
    <!-- 页面标题和搜索区域 -->
    <el-card class="header-card">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">积分明细管理</h2>
          <p class="page-subtitle">查看和管理所有用户的积分信息</p>
        </div>
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户昵称或OpenID..."
            clearable
            style="width: 300px; margin-right: 10px;"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="refreshData" :loading="loading">
            刷新数据
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计信息卡片 -->
    <el-card class="stats-card" v-if="stats">
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-value">{{ stats.totalUsers }}</div>
          <div class="stat-label">总用户数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.totalBalance }}</div>
          <div class="stat-label">总积分余额</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.avgBalance }}</div>
          <div class="stat-label">平均积分</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ stats.zeroBalanceUsers }}</div>
          <div class="stat-label">零积分用户</div>
        </div>
      </div>
    </el-card>

    <!-- 用户积分表格 -->
    <el-card class="users-card">
      <template #header>
        <div class="card-header">
          <span>用户积分列表</span>
          <div class="header-actions">
            <el-select v-model="sortBy" placeholder="排序方式" style="width: 120px; margin-right: 10px;" @change="handleSort">
              <el-option label="积分倒序" value="balance-desc" />
              <el-option label="积分正序" value="balance-asc" />
              <el-option label="注册时间倒序" value="time-desc" />
              <el-option label="注册时间正序" value="time-asc" />
            </el-select>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table 
          :data="paginatedUsers" 
          style="width: 100%"
          :max-height="500"
          v-loading="loading"
          stripe
        >
          <template #empty>
            <div class="empty-state">
              <el-icon size="48" color="#909399">
                <Document />
              </el-icon>
              <p>暂无用户数据</p>
            </div>
          </template>
          
          <el-table-column prop="id" label="用户ID" width="80" align="center" />
          
          <el-table-column prop="avatar" label="头像" width="80" align="center">
            <template #default="{ row }">
              <img :src="getAvatarUrl(row.avatar)" alt="头像" class="user-avatar" @error="handleImageError" />
            </template>
          </el-table-column>
          
          <el-table-column prop="nickname" label="用户昵称" width="120" show-overflow-tooltip />
          
          <el-table-column prop="openid" label="OpenID" width="200" show-overflow-tooltip />
          
          <el-table-column prop="balance" label="当前积分" width="120" align="center">
            <template #default="{ row }">
              <span class="balance-amount" :class="getBalanceClass(row.balance)">
                {{ row.balance || 0 }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column prop="memberType" label="会员类型" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getMemberTypeTag(row.memberType)" size="small">
                {{ getMemberTypeText(row.memberType) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                {{ row.status === 1 ? '正常' : '封禁' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createdTime" label="注册时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.createdTime) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewPointDetail(row)">
                查看积分
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="filteredUsers.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredUsers.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 积分明细对话框 -->
    <el-dialog 
      v-model="pointDetailDialogVisible" 
      title="用户积分明细" 
      width="90%"
      class="point-detail-dialog"
      :close-on-click-modal="false"
    >
      <PointDetail v-if="pointDetailDialogVisible" :openid="selectedUserOpenid" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointDetailDialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Document, Search, Close } from "@element-plus/icons-vue";
import PointDetail from "./PointDetail.vue";
import usersapi from "../api/usersapi";

// 响应式数据
const loading = ref(false);
const users = ref([]);
const stats = ref(null);
const currentPage = ref(1);
const pageSize = ref(20);
const searchKeyword = ref('');
const sortBy = ref('balance-desc');
const pointDetailDialogVisible = ref(false);
const selectedUserOpenid = ref('');

// 计算过滤后的数据
const filteredUsers = computed(() => {
  let result = users.value;
  
  // 搜索过滤
  if (searchKeyword.value) {
    result = result.filter(user => 
      user.nickname?.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      user.openid?.toLowerCase().includes(searchKeyword.value.toLowerCase())
    );
  }
  
  // 排序
  result = [...result].sort((a, b) => {
    switch (sortBy.value) {
      case 'balance-desc':
        return (b.balance || 0) - (a.balance || 0);
      case 'balance-asc':
        return (a.balance || 0) - (b.balance || 0);
      case 'time-desc':
        return new Date(b.createdTime) - new Date(a.createdTime);
      case 'time-asc':
        return new Date(a.createdTime) - new Date(b.createdTime);
      default:
        return 0;
    }
  });
  
  return result;
});

// 计算分页后的数据
const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredUsers.value.slice(start, end);
});

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 排序处理
const handleSort = () => {
  currentPage.value = 1;
};

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar || avatar === '' || avatar === 'null' || avatar === 'undefined') {
    return '';
  }
  
  if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
    return avatar;
  }
  
  const baseUrl = 'http://tool_back.connectsphere.top';
  return baseUrl + (avatar.startsWith('/') ? avatar : '/' + avatar);
};

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.src = '';
};

// 获取会员类型标签颜色
const getMemberTypeTag = (type) => {
  switch (type) {
    case 0: return 'info';    // 普通
    case 1: return 'warning'; // 月度
    case 2: return 'success'; // 年度
    default: return 'info';
  }
};

// 获取会员类型文本
const getMemberTypeText = (type) => {
  switch (type) {
    case 0: return '普通';
    case 1: return '月度';
    case 2: return '年度';
    default: return '普通';
  }
};

// 获取积分样式类
const getBalanceClass = (balance) => {
  const bal = balance || 0;
  if (bal > 1000) return 'high-balance';
  if (bal > 100) return 'medium-balance';
  if (bal > 0) return 'low-balance';
  return 'zero-balance';
};

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  
  try {
    const date = new Date(dateTime);
    if (isNaN(date.getTime())) {
      const parsedDate = new Date(dateTime.replace(/-/g, '/'));
      if (!isNaN(parsedDate.getTime())) {
        return formatDate(parsedDate);
      }
      return dateTime;
    }
    return formatDate(date);
  } catch (e) {
    console.error('格式化时间出错:', e);
    return dateTime;
  }
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 查看积分明细
const viewPointDetail = (user) => {
  selectedUserOpenid.value = user.openid;
  pointDetailDialogVisible.value = true;
};

// 获取用户数据
const fetchUserData = async () => {
  loading.value = true;
  
  try {
    const response = await usersapi.getUserlist();
    
    if (response.data) {
      users.value = response.data;
      
      // 计算统计信息
      const totalUsers = users.value.length;
      const totalBalance = users.value.reduce((sum, user) => sum + (user.balance || 0), 0);
      const avgBalance = totalUsers > 0 ? Math.round(totalBalance / totalUsers) : 0;
      const zeroBalanceUsers = users.value.filter(user => !user.balance || user.balance === 0).length;
      
      stats.value = {
        totalUsers,
        totalBalance,
        avgBalance,
        zeroBalanceUsers
      };
      
      ElMessage.success('数据加载成功');
    } else {
      console.error('API返回的数据为空');
      ElMessage.error('API返回的数据为空');
    }
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  fetchUserData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchUserData();
});
</script>

<style scoped>
.point-details-section {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.header-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 4px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1976d2;
}

.page-subtitle {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-section {
  display: flex;
  align-items: center;
}

.stats-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e3f2fd;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e3f2fd;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1976d2;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.users-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-container {
  margin-bottom: 20px;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e3f2fd;
  transition: all 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3);
}

.balance-amount {
  font-weight: bold;
  font-size: 16px;
}

.high-balance {
  color: #4caf50;
}

.medium-balance {
  color: #ff9800;
}

.low-balance {
  color: #2196f3;
}

.zero-balance {
  color: #f44336;
}

.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  background: #fff;
  border-radius: 8px;
  margin-top: 16px;
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.1);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state p {
  margin-top: 16px;
  font-size: 16px;
}

/* 积分明细对话框样式 */
:deep(.point-detail-dialog .el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.point-detail-dialog .el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

:deep(.point-detail-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

:deep(.point-detail-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.point-detail-dialog .el-dialog__footer) {
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .search-section {
    width: 100%;
    flex-direction: column;
    gap: 10px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    flex-direction: column;
    gap: 10px;
  }
}
</style>